package com.coder4j.config;

import com.coder4j.starter.web.cache.AuthCache;
import com.coder4j.starter.web.util.AuthUtils;
import com.coder4j.starter.web.jwt.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户拦截器，获取到登录的用户信息，放入ThreadLocal中
 * @author keller
 * @date 2024-5-16 14:29:26
 */
@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Resource
    private AuthCache authCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("----------UserInterceptor--{}",request.getRequestURI());
        // 检查是否是WebSocket Upgrade请求
        if ("WebSocket".equalsIgnoreCase(request.getHeader("Upgrade"))) {
            // 如果是WebSocket Upgrade请求，则直接放行
            return true;
        }
        log.info("----------UserInterceptor running--{}",request.getRequestURI());
        Long userId = TokenUtils.getUserId(request);
        if(userId != null){
            //ThreadLocal 存入用户角色
            AuthUtils.setAuthVO(authCache.getAuthUserCache(userId));
        }
        return true;
    }
}
